'use strict';
const fs = require('fs');

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');
const axios = require('axios');
var FormData = require('form-data');

class BlogController extends Controller {
  async getBlogById() {
    const { id } = this.ctx.params;
    try {
      const blog = await this.ctx.model.Blog.findById(id);
      if (blog) {
        this.ctx.body = {
          code: 0,
          msg: 'ok',
          data: blog
        };
      } else {
        this.ctx.body = {
          code: -1,
          msg: '未找到对应的博客数据'
        };
      }
    } catch (error) {
      this.ctx.body = {
        code: -1,
        msg: '查询博客数据时出错',
        error: error.message
      };
    }
  }
  async addBlog() {
    const { name, avatar, content } = this.ctx.request.body;
    try {
      const res = await this.ctx.model.Blog.create({
        avatar: 'https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/073c0ec57ce633ba8d80c73713470f12?f=webp&w=96&thumb=1',
        name: 'sun2000cn',
        content: '哈哈，大家快来打卡签到，获得2025米粉节勋章。',
        images: ['https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/4de25f7b8ccdf7fdd315aa29e775a351?f=webp&thumb=1&w=960&q=80'],
        date: '21小时前',
        likes: 200,
        comments: [],
        shares: 190
      });
      this.ctx.body = {
        retcode: 1,
        msg: res
      };
    } catch (err) {
      this.ctx.body = {
        retcode: -1,
        msg: err
      };
    }
  }
  async getAllBlogs() {
    try {
      const blogs = await this.ctx.model.Blog.find({});
      this.ctx.body = {
        code: 0,
        msg: 'ok',
        data: blogs
      };
    } catch (error) {
      this.ctx.body = {
        code: -1,
        msg: '查询所有博客数据时出错',
        error: error.message
      };
    }
  }
  async addComment() {
    const { id, comment } = this.ctx.request.body;


    // 获取当前用户id
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    const user = await this.ctx.model.User.findById(decoded.id);

    try {
      const blog = await this.ctx.model.Blog.findById(id);
      if (blog) {
        blog.comments.push({
          comment,
          date: new Date(),
          name: user.username,
        });
        await blog.save();
        this.ctx.body = {
          code: 0,
          msg: '评论添加成功',
          data: blog
        };
      } else {
        this.ctx.body = {
          code: -1,
          msg: '未找到对应的博客数据'
        };
      }
    } catch (error) {
      this.ctx.body = {
        code: -1,
        msg: '添加评论时出错',
        error: error.message
      };
    }
  }

  async addLike() {
    const { id } = this.ctx.params;
    try {
      const blog = await this.ctx.model.Blog.findById(id);
      if (blog) {
        blog.likes += 1;
        await blog.save();
        this.ctx.body = {
          code: 0,
          msg: '点赞成功'
        };
      } else {
        this.ctx.body = {
          code: -1,
          msg: '未找到对应的博客数据'
        };
      }
    } catch (error) {
      this.ctx.body = {
        code: -1,
        msg: '点赞时出错',
        error: error.message
      };
    }
  }

  async getGroup() {
    this.ctx.body = {
      success: true,
      data: [{
        name: '摄影馆',
        num: '53.2万+人',
        image: 'https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/f4b9d21bc79dd2dc11988ce488597427?f=webp&w=1504&thumb=1'
      }, {
        name: '米粉杂谈',
        num: '28.6万+人',
        image: 'https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/3ae4759bbbf0073ca01fdb5911b7da6e?f=webp&w=1504&thumb=1'
      }, {
        name: '小米社区',
        num: '52.2万+人',
        image: 'https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/8caf6c5af2669fa783c91e67dad05de9?f=webp&w=1504&thumb=1'
      }, {
        name: '手环',
        num: '17.1万+人',
        image: 'https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/8bc0ac50fd6e29ee59201938efce4710?f=webp&w=1504&thumb=1'
      }, {
        name: '小米手表',
        num: '11.8万+人',
        image: 'https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/c46920d464cd6230438dc409b445af76?f=webp&w=1504&thumb=1'
      }, {
        name: '平板综合讨论',
        num: '34.4万+人',
        image: 'https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/f22d3b83ad31e2d41230f09df6cdfa81?f=webp&w=1504&thumb=1'
      }]
    }
  }

  async saveGroup() {
    const { ctx } = this;
    const { group } = ctx.request.body;

    // 获取当前用户id
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");

    try {
      // 查询当前用户在menu表中是否有记录
      const existingMenu = await ctx.model.Menu.findOne({ userId: decoded.id });
      if (existingMenu) {
        // 如果有记录，更新数据
        existingMenu.menus.push(group);
        const result = await existingMenu.save();
        ctx.body = { success: true, data: result };
      } else {
        // 如果没有记录，新增数据
        const result = await ctx.model.Menu.create({ menus: [group], userId: decoded.id });
        ctx.body = { success: true, data: result };
      }
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  async myGroup() {
    const { ctx } = this;
    const { keyword } = ctx.request.query;
    // 获取当前用户id
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    try {
      const result = await ctx.model.Menu.find({ userId: decoded.id });
      if (result.length == 0) {
        ctx.body = {
          success: true,
          data: []
        };
      } else {
        ctx.body = {
          success: true,
          data: [{
            name: '摄影馆',
            num: '53.2万+人',
            image: 'https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/f4b9d21bc79dd2dc11988ce488597427?f=webp&w=1504&thumb=1'
          }, {
            name: '米粉杂谈',
            num: '28.6万+人',
            image: 'https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/3ae4759bbbf0073ca01fdb5911b7da6e?f=webp&w=1504&thumb=1'
          }, {
            name: '小米社区',
            num: '52.2万+人',
            image: 'https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/8caf6c5af2669fa783c91e67dad05de9?f=webp&w=1504&thumb=1'
          }, {
            name: '手环',
            num: '17.1万+人',
            image: 'https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/8bc0ac50fd6e29ee59201938efce4710?f=webp&w=1504&thumb=1'
          }, {
            name: '小米手表',
            num: '11.8万+人',
            image: 'https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/c46920d464cd6230438dc409b445af76?f=webp&w=1504&thumb=1'
          }, {
            name: '平板综合讨论',
            num: '34.4万+人',
            image: 'https://cdn.cnbj1.fds.api.mi-img.com/middle.community.vip.bkt/f22d3b83ad31e2d41230f09df6cdfa81?f=webp&w=1504&thumb=1'
          }].filter((item) => {
            return result[0].menus.includes(item.name)
          })
        };
      }

    }
    catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  async similar() {
    const { ctx } = this;
    const { text1, text2 } = ctx.request.body;

    try {
      const res = await axios.get(`https://api.pearktrue.cn/api/textdifference?text1=${text1}&text2=${text2}`)

      if (res.data.code == 500) {
        this.ctx.body = {
          code: -1,
          msg: '相似度计算时出错',
          data: {
            data: {
              "similarity": "0.3%",
            }
          }
        }
      } else {
        this.ctx.body = {
          code: 0,
          msg: 'ok',
          data: res.data
        }
      }

    } catch (error) {
      this.ctx.body = {
        code: -1,
        msg: '相似度计算时出错',
        data: {
          "similarity": "0.3%",
        }
      };
    }

  }

  async population() {
    const { ctx } = this;
    const { text1, text2 } = ctx.request.body;

    const res = await axios.get(`https://api.pearktrue.cn/api/human/rank.php`)

    this.ctx.body = {
      code: 0,
      msg: 'ok',
      data:
        res.data.data.map((item) => {
          return {
            ...item,
            quantity: Number(item.quantity.replace(/\s/g, ""))
          }
        })
    }
  }
}



module.exports = BlogController;